<template>
  <div class="drill-down-table">
    <div class="drill-down-table-button"> 
      <div class="position-time" v-if="positionTime">当前统计时间：{{positionTime}}</div>
      <el-radio-group
        v-model="tableSelectTabs"
        @change="changeTableSelectTabs"
      >
        <el-radio-button
          v-for="item in tabsData"
          :key="item.label"
          :label="item.label"
        >
          {{item.value}}
        </el-radio-button>
      </el-radio-group>

      <div>
        <!-- 只有下钻到工单的需要在列表中打开 先不做了-->
        <!-- <el-button @click="jumpList" plain>在列表中打开</el-button> -->
        <el-button 
          v-show="isTaskReturnVisit && isShowExportBtn && isWhiteList && allowExport" 
          @click="exportTableData(false)" 
          type="primary"
        >导出</el-button>
        <el-button 
          v-show="isShowExportBtn && isWhiteList && allowExport" 
          @click="exportTableData(true)" 
          type="primary"
        >导出全部</el-button>
        <el-button @click="foldTable" plain>收起</el-button>
      </div>
    </div>
    <!-- 及时关单率/重复维修率 要显示周期tab -->
    <!-- 工单客户满意度/重复维修率 要显示品类tab -->
    <!-- 及时关单率 -->
    <el-radio-group
      size="mini"
      v-model="tablePeriodSelectValue"
      @change="changePeriodTableSelectTabs"
    >
      <el-radio-button
        v-for="item in periodTabsData"
        :key="item.label"
        :label="item.label"
      >
        {{item.value}}
      </el-radio-button>
    </el-radio-group>

    <div v-if="closingList.length > 0">
      <div
        v-for="(item, index) in closingList"
        :key="index"
      >
        <el-table
          :data="item.tableList"
          border
          :header-cell-style="{'background-color': '#FAFAFA'}"
          @cell-click="getCellData">

          <el-table-column v-for="(column, index) in columns" 
            :key="`${column.prop}_${index}`"
            :label="column.label"
            :prop="column.prop"
            :min-width="column.minWidth"
            :show-overflow-tooltip="column.tooltip">

            <template slot-scope="scope">
              
              <template v-if="scope.row[`${column.prop}_most`]">
                <span class="table-high-light">
                  {{scope.row[`${column.prop}`]}}
                </span>
              </template>

              <template v-else-if="column.prop == 'customerName'">
                <span :class="{'link-text': !isExample && isAuthCustomer}">
                  <template>
                    {{ scope.row[`${column.prop}`] }}
                  </template>
                </span>
              </template>

              <template v-else-if="column.prop == 'taskNo'">
                <span :class="{'link-text': !isExample && isAuthTask}">
                  <template>
                    {{ scope.row[`${column.prop}`] }}
                  </template>
                </span>
              </template>
              
              <template v-else-if="column.prop == 'userName'">
                <span :class="{'link-text': !isExample && repeatedMaintenanceAuth}">
                <template v-if="isOpenData && scope.row.userStaffId">
                  <open-data type="userName" :openid="scope.row.userStaffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row[`${column.prop}`] }}
                </template>
                </span>
              </template>
              
              <template v-else-if="column.prop == 'synergiesName'">
                <!-- // TODO: 微信人员open-data -->
                <template v-if="isOpenData && scope.row.synergiesStaffId">
                  <!-- // TODO: 微信人员open-data -->
                  <open-data type="userName" :openid="scope.row.synergiesStaffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row[`${column.prop}`] }}
                </template>
              </template>
              
              <template v-else-if="column.prop == 'reviewUserName'">
                <!-- // TODO: 微信人员open-data -->
                <template v-if="isOpenData && scope.row.reviewStaffId">
                  <!-- // TODO: 微信人员open-data -->
                  <open-data type="userName" :openid="scope.row.reviewStaffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row[`${column.prop}`] }}
                </template>
              </template>
              
              <template v-else-if="column.prop == 'name'">
                <span :class="{'link-text': !isExample && typeAuth}">
                  <template v-if="isOpenData && scope.row.userStaffId">
                    <open-data type="userName" :openid="scope.row.userStaffId"></open-data>
                  </template>
                  <template v-else>
                    {{ scope.row[`${column.prop}`] }}
                  </template>
                </span>
              </template>
              
              <template v-else>
                {{ scope.row[`${column.prop}`] }}
              </template>
            </template>

          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 平均服务用时下钻列表 -->
    <div v-else>
      <el-table
        :data="tableList"
        border
        :header-cell-style="{'background-color': '#FAFAFA'}"
        @cell-click="getCellData">

        <el-table-column v-for="(column, index) in columns" 
          :key="`${column.field}_${index}`"
          :label="column.label"
          :prop="column.prop"
          :min-width="column.minWidth"
          :show-overflow-tooltip="column.tooltip">
            
            <template slot-scope="scope">

              <template v-if="scope.row[`${column.prop}_most`]">
                <span class="table-high-light">
                  {{scope.row[`${column.prop}`]}}
                </span>
              </template>

              <template v-else-if="column.prop == 'customerName'">
                <span :class="{'link-text': !isExample && isAuthCustomer}">
                  <template>
                    {{ scope.row[`${column.prop}`] }}
                  </template>
                </span>
              </template>

              <template v-else-if="column.prop == 'taskNo'">
                <span :class="{'link-text': !isExample && isAuthTask}">
                  <template>
                    {{ scope.row[`${column.prop}`] }}
                  </template>
                </span>
              </template>
              
              <template v-else-if="column.prop == 'userName'">
                <span :class="{'link-text': !isExample && repeatedMaintenanceAuth}">
                <template v-if="isOpenData && scope.row.userStaffId">
                  <open-data type="userName" :openid="scope.row.userStaffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row[`${column.prop}`] }}
                </template>
                </span>
              </template>

              <template v-else-if="column.prop == 'synergiesName'">
                <!-- // TODO: 微信人员open-data -->
                <template v-if="isOpenData && scope.row.synergiesStaffId">
                  <!-- // TODO: 微信人员open-data -->
                  <open-data type="userName" :openid="scope.row.synergiesStaffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row[`${column.prop}`] }}
                </template>
              </template>
              
              <template v-else-if="column.prop == 'reviewUserName'">
                <!-- // TODO: 微信人员open-data -->
                <template v-if="isOpenData && scope.row.reviewStaffId">
                  <!-- // TODO: 微信人员open-data -->
                  <open-data type="userName" :openid="scope.row.reviewStaffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row[`${column.prop}`] }}
                </template>
              </template>
              
              <template v-else-if="column.prop == 'name'">
                <span :class="{'link-text': !isExample && typeAuth}">
                  <template v-if="isOpenData && scope.row.userStaffId">
                    <open-data type="userName" :openid="scope.row.userStaffId"></open-data>
                  </template>
                  <template v-else>
                    {{ scope.row[`${column.prop}`] }}
                  </template>
                </span>
              </template>
              
              <template v-else>
                {{ scope.row[`${column.prop}`] }}
              </template>
              
            </template>
            
        </el-table-column>

      </el-table>
    </div>

    <!-- 分页 -->
    <div v-if="hidePagination" class="drill-down-pagination-wrap">
      <el-pagination
        class="drill-down-pagination"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="tablePageParams.page"
        :page-sizes="defaultTableData.defaultPageSizes"
        :page-size="tablePageParams.pageSize"
        :layout="defaultTableData.defaultLayout"
        :total="tablePageParams.totalSize"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
/* vue */
import { 
  ref,
  computed,
  watch,
  onMounted
} from 'vue'
/* model */
import {
  builsTabsData,
  buildColumns,
  buildsPeriodTabsData
} from './useChartData'
/* util */
import { getRootWindowInitData } from '@src/util/window'
import { 
  openTabForUserView, 
  openTabForProductView, 
  openTabForCustomerView, 
  openTabForTagHome, 
  openTabServiceProviderHome,
} from '@src/util/business/openTab'
import _ from 'lodash';
import platform from '@src/platform'

import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { defaultTableData } from '@src/util/table'

/* const */
const initData = getRootWindowInitData()
/* components */
import BaseTableCell from 'packages/BaseTableCell';

export default {
  name: 'drill-down-table',
  props: {
    chartType: {
      type: String,
      default: ''
    },
    tableData: {
      type: Array,
      default: () => ([])
    },
    pieTableData: {
      type: Array,
      default: () => ([])
    },
    lineTableData: {
      type: Array,
      default: () => ([])
    },
    tablePageParams: {
      type: Object,
      default: () => ({})
    },
    // 单位
    timeUnit: {
      type: Number,
      default: 1
    },
    chartOption: {
      type: Object,
      default: () => ({})
    },
    tablePeriodSelectTabs: {
      type: String,
      default: '0'
    },
    userModuleAuth: {
      type: Object,
      default: ()=> ({})
    },
    positionTime: {
      type: String,
      default: ''
    }
  },
  computed: {
    isCloseTaskTable() {
      return this.chartType === 'timely-closing-rate'
    },
    isTaskReturnVisit() {
      return this.chartType === 'task-return-visit'
    },
    // 企微导出权限
    isWhiteList() {
      const { tenantType, WHITE_LIST } = initData;
      if (tenantType == 2) {
        return WHITE_LIST;
      }
      return true;
    },
    auth() {
      return initData?.user?.auth || initData?.loginUser?.authorities;
    },
    // 导出权限
    allowExport() {
      return this.auth?.REPORT_EXPORT;
    },
  },
  components: {
    [BaseTableCell.name]: BaseTableCell,
  },
  data() {
    return {}
  },
  setup(props, { emit }) {
    let tabsData = ref([])
    const periodTabsData = ref([])
    // const tablePeriodSelectTabs = ref('0')
    const tablePeriodSelectValue = ref('0')

    const tablePeriodSelect = computed(() => {
      return props.tablePeriodSelectTabs
    })
    watch(tablePeriodSelect, (n) => {
      tablePeriodSelectValue.value = n
    })
    
    const getTabsData = () => {
      tabsData.value = builsTabsData(props)
    }

    const tableSelectTabs = ref('MAN')
    const ousideSelectType = computed(() => {
      if(props.chartType === 'repeated-maintenance-rate') {
        return props.chartOption?.selectType
      } else {
        return props.chartOption?.ousideSelectType
      }
    })

    watch(ousideSelectType, (n,o) => {
      tableSelectTabs.value = n
    })
    
    const changeTableSelectTabs = value => {
      let newValue = null
      if(props.chartType === 'repeated-maintenance-rate') {
        newValue = {
          ...props.chartOption,
          selectType: value
        }
      } else {
        newValue = {
          ...props.chartOption,
          ousideSelectType: value
        }
      }
      // tablePeriodSelectTabs.value = '0'
      emit('changePeriodTableSelectTabs', '0')
      emit('fetchTableData', newValue, null, 'tab')
    }

    // 周期
    let activeName = ref('0') 
    const foldTable = _ => {
      activeName.value = '0'
      emit('foldTable', false);
    }

    // 及时关单率tab
    const getPeriodTabsData = () => {
      periodTabsData.value = buildsPeriodTabsData(props)
    }

    const aroundSearchQueryList = computed(() => {
      return props.chartOption?.aroundSearchQueryList
    }) 

    const changePeriodTableSelectTabs = value => {
      // tablePeriodSelectTabs.value = value
      emit('changePeriodTableSelectTabs', value + '')
      const newValue = ref(null)
      if (props.chartType === 'timely-closing-rate') {
        // 及时关单率
        newValue.value = props.chartOption?.aroundSearchQueryList[value]
      } else if (props.chartType === 'repeated-maintenance-rate') {
        // 重复维修率
        newValue.value = props.chartOption?.repeatedSearchQueries[value]
      }
      emit('fetchTableData', newValue.value, null, 'closeTab')
    }
    
    watch(aroundSearchQueryList, (n, o) => {
      // tablePeriodSelectTabs.value = '0'
      emit('changePeriodTableSelectTabs', '0')
    })

    // 是否开启示例
    const isExample = computed(() => {
      return props.chartOption?.isExample;
    })

    // 在列表中打开
    const jumpList = () => {
      // 工单类型 部门 人员 回访时间 要找产品确认工单类型多选的问题 
      // 先不做了
      window.location.href = ''
    }
    
    const jump = (row) => {
      const id = row?.id
      if (!id) return
      
      if (ousideSelectType.value == 'MAN') {
        openTabForUserView(id)
      }
      else if (ousideSelectType.value == 'PRODUCT') {
        isJumpProduct(id);
      }
      else if (ousideSelectType.value == 'CUSTOMER') {
        isJumpCustomer(id);
      }
      else if (ousideSelectType.value == 'SERVICEPROVIDER') {
        if(row.type === 0){
          openTabForTagHome(id);
        }else if(row.type === 1) {
          openTabServiceProviderHome(id);
        }
      }
    }

    // 工单客户满意度 满意度构成下钻权限
    const typeAuth = computed(() => {
      if (ousideSelectType.value == 'PRODUCT') {
        return isAuthProduct.value;
      } else if(ousideSelectType.value == 'CUSTOMER') {
        return isAuthCustomer.value;
      } else{
        return true;
      }
    })
    // 重复维修率 产品下钻权限
    const repeatedMaintenanceAuth = computed(() => {
      if(props.chartType === 'repeated-maintenance-rate') {
        if(props.chartOption.selectType === 'PRODUCT') return isAuthProduct.value;
      }
      return true;
    })

    // 模块权限
    const isAuthTask= computed(() => {
      return props.userModuleAuth?.authTask;
    })
    const isAuthProduct = computed(() => {
      return props.userModuleAuth?.authProduct;
    })
    const isAuthCustomer = computed(() => {
      return props.userModuleAuth?.authCustomer;
    })

    // 工单跳转权限
    const isJumpTask = (id, taskNo)=>{
      if(!isAuthTask.value) return;
      openTabForTaskView(id, taskNo);
    }
    // 产品跳转权限
    const isJumpProduct = (id)=>{
      if(!isAuthProduct.value) return;
      openTabForProductView(id);
    }
    // 客户跳转权限
    const isJumpCustomer = (id)=>{
      if(!isAuthCustomer.value) return;
      openTabForCustomerView(id);
    }

    // 切换周期tab
    const handleClick = _ => {
      // 切换tab没有重新请求接口 分页不能重置到1
      // props.tablePageParams.page = 1
    }

    const handleSizeChange = value => {
      emit('handleSizeChange', value)
    };

    const handleCurrentChange = value => {
      emit('handleNumChange', value)
    };

    const getCellData = (row, column) => {
      // 如果为 人员名称/产品名称/客户名称/部门名称列，且为系统管理员，则跳转到详情页
      if(isExample.value) return emit('getCellData', row, column);

      if (column.property == 'name') {
        return jump(row)
      }
      // 人员详情
      if (column.property == 'userName') {
        const id = row.id || row.userId || '';
        // 重复维修率
        if(props.chartType === 'repeated-maintenance-rate') {
          if(row.selectType === 'PRODUCT') return isJumpProduct(id);
        }else if(props.chartType === 'task-return-visit') {
          return openTabForUserView(row.userId);
        }
        return id && openTabForUserView(id);
      }else if (column.property == 'taskNo') {
        // 工单详情
        return row.id && isJumpTask(row.id, row.taskNo);
      }else if (column.property == 'customerName') {
        // 客户详情
        return row.customerId && isJumpCustomer(row.customerId);
      }
      
      emit('getCellData', row, column)
    }

    const exportTableData = value => {
      if (value) {
        emit('export')
      } else {
        emit('export', null, props.tablePageParams)
      }
    }

    // 构造table数据
    let columns = ref([])
    let tableList = ref([])
    let closingList = ref([])
    let hidePagination = ref(false)
    const totalData = computed(_ => {
      let data = [props.tableData, props.pieTableData, props.lineTableData]
      return data.filter(item => item.length > 0).shift() || []
    })

    watch(totalData, (n,o) => {
      
      let { columnsData = [], tableData = [], closingData = [] } =  buildColumns(props)
      // 无数据时隐藏表头和分页
      if (n.length > 0) {
        columns.value = columnsData
        hidePagination.value = true
      } else {
        columns.value = []
        hidePagination.value = false
      }
      tableList.value = tableData
      closingList.value = closingData
      getPeriodTabsData()
      getTabsData()
    })

    // 导出功能是否展示：表格有数据 && 不为示例数据
    const isShowExportBtn = computed(() => {
      return (tableList.value.length > 0 || closingList.value.length > 0) && !props.chartOption?.isExample;
    })

    // 跳转工单
    const openTabForTaskView = (taskId = '',taskNo = '', isNoHistory = true, isBalance = false, isAllot = false) => {
      if (!taskId) return;
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type:PageRoutesTypeEnum.PageTaskView,
        key:taskId,
        params:`${isNoHistory ? 'noHistory=1' : ''}${isBalance ? isNoHistory ? '&active=balance' : 'active=balance' : ''}${isAllot ? '&allot=true' : ''}`,
        fromId
      })
    }

    onMounted(() => {
      
    })

    return {
      defaultTableData,
      totalData,
      tabsData,
      periodTabsData,
      tableSelectTabs,
      // tablePeriodSelectTabs,
      tablePeriodSelectValue,
      activeName,
      columns,
      tableList,
      closingList,
      hidePagination,
      changeTableSelectTabs,
      changePeriodTableSelectTabs,
      foldTable,
      handleSizeChange,
      handleCurrentChange,
      handleClick,
      jumpList,
      getCellData,
      jump,
      exportTableData,
      isShowExportBtn,
      isExample,
      typeAuth,
      isAuthTask,
      isAuthProduct,
      isAuthCustomer,
      repeatedMaintenanceAuth,
    };
  }
};
</script>

<style lang="scss" scoped>
.drill-down-table {
  padding: 0 1%;
  margin-top: 20px;
  width: 100%;

  .drill-down-table-button {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    .position-time {
      display: inline-block;
      line-height: 30px;
      font-size: 14px;
      height: 30px;
      font-weight: bold;
    }
  }

  .drill-down-select {
    margin-left: 20px;
  }

  span {
    font-size: 13px;
    // font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 400;
    color: #666;
  }

  .el-table {
    position: relative;
    overflow: hidden;
    box-sizing: border-box;
    flex: 1 1 0%;
    width: 100%;
    max-width: 100%;
    margin: 16px 0;
    border-top: 1px solid #ebeef5;
    border-left: 1px solid #ebeef5;
    ::v-deep .el-table__empty-block {
      border-right: 1px solid #ebeef5;
      border-bottom: 1px solid #ebeef5;
    }
  }

  .table-high-light {
    color: $color-primary-light-6;
  }
  
  .drill-down-pagination-wrap {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
  } 
  .drill-down-pagination {
    width: 100%;
    flex: 1;
    text-align: right;
    // justify-content: end;
    // position: relative;

    ::v-deep .el-pagination__total {
      // position: absolute;
      // left: 0;
    }

    ::v-deep .el-pagination__sizes {
      // position: absolute;
      // left: 70px;
    }
  }
}
</style>
<style lang="scss">
.drill-down-table {
  .cell {
    cursor: pointer;
  }
}
</style>